package com.ht.api.service;

import java.io.File;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import com.ht.api.db.util.WxFileUtils;
import com.ht.api.open.OpenUtil;
import com.ht.api.open.TokenService;
import com.ht.api.oss.AliyunOssUploadUtils;
import com.ht.api.util.Mp3Util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 微信公众号service
 * @author asq
 * @createTime 2025年4月7日 19:01:54
 */
@Slf4j
public class OfficialService {
	/** 接口：微信公众号上传素材 */
	private static final long API_ID_UPLOAD_OFFICIAL = 1891784559327055872L;
	/** 获取token的服务类 */
	private static TokenService tokenService = SpringUtil.getBean(TokenService.class);
	
	/** 消息类型简略描述 */
	private static Map<String, String> msgMap = new HashMap<>();
	static {
		msgMap.put("image", "[图片]");
		msgMap.put("voice", "[语音]");
		msgMap.put("video", "[视频]");
		msgMap.put("shortvideo", "[小视频]");
		msgMap.put("file", "[文件]");
		msgMap.put("location", "[位置]");
		msgMap.put("link", "[链接]");
		msgMap.put("business_card", "[名片]");
		msgMap.put("miniprogram", "[小程序]");
		msgMap.put("msgmenu", "[菜单]");
		msgMap.put("channels_shop_product", "[视频号商品]");
		msgMap.put("channels_shop_order", "[视频号订单]");
		msgMap.put("merged_msg", "[聊天记录]");
		msgMap.put("channels", "[视频号]");
		msgMap.put("meeting", "[会议]");
		msgMap.put("calendar", "[日程]");
		msgMap.put("note", "[笔记]");
	}

    public static String getTempImageMediaId (String appId, String url) {
        return getTempMediaId(appId, "image", url);
    }

    public static String getTempVideoMediaId (String appId, String url) {
        return getTempMediaId(appId, "video", url);
    }

    public static String getTempVoiceMediaId (String appId, String url) {
        return getTempMediaId(appId, "voice", url);
    }

    public static String getTempFileMediaId (String appId, String url) {
        return getTempMediaId(appId, "file", url);
    }

	/**
	 * 上传临时素材
	 * @param appId
	 * @param type
	 * @param url
	 * @return
	 */
    public static String getTempMediaId (String appId, String type, String url) {
        JSONObject fileParam = JSONUtil.createObj();
        fileParam.set("type", type);
        fileParam.set("oss_url", url);
        String imageResult = OpenUtil.call(appId, API_ID_UPLOAD_OFFICIAL, fileParam);
        String imageMediaId = JSONUtil.parseObj(imageResult).getStr("media_id");

        return imageMediaId;
    }

	/**
	 * 获取客户发送的消息
	 * @param msg
	 * @return
	 */
    public static String formatMsg(JSONObject msg) {
    	String msgtype = msg.getStr("MsgType");
		if ("text".equals(msgtype)) {
			return msg.getByPath("Content", String.class);
		} else {
			String shortMsg = msgMap.get(msgtype);
			if (shortMsg != null) {
				return shortMsg;
			} else {
				return "";
			}
		}
	}
    
    /**
     * 下载公众号素材，并上传到阿里云
     * @param mediaId 素材ID
     * @param ext 扩展名
     * @return
     */
    public static String uploadFileToAliyun(String mediaId) {
    	// 下载素材
    	String url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s";
		String token = tokenService.getToken(1899457251115143168L, "1899457676526620672");
		File file = WxFileUtils.downFile(String.format(url, token, mediaId));
		String ext = FileUtil.extName(file);
		
		// 处理语音文件
		File convertFile = file;
		if ("amr".equals(ext)) {
			convertFile = Mp3Util.convertAmrToMp3(file);
			ext = FileUtil.extName(convertFile);
		}
		
		// 上传
		String path = null;
		try {
			log.info("上传公众号素材到阿里云，素材ID：{}，扩展名：{}", mediaId, ext);
			path = AliyunOssUploadUtils.uploadFile(file, mediaId + "." + ext);
		} catch (Exception e) {
			log.error("上传公众号素材文件到阿里云出现异常：{}", e.getMessage(), e);
		}
		
		// 删除临时文件
		try {
			if (!file.delete()) {
		        file.deleteOnExit();
		    }
			if (!convertFile.delete()) {
				convertFile.deleteOnExit();
			}
			file.getParentFile().delete();
			
			log.info("上传公众号素材文件到阿里云成功，已删除临时文件：{}", mediaId + "." + ext);
		} catch (Exception e) {
			log.info("上传公众号素材文件到阿里云成功，删除临时文件出现异常：{}", e.getMessage(), e);
		}
    	
    	return path;
    }
    
    /**
     * 根据ticket获取二维码，并上传到阿里云上
     * @param ticket
     * @return
     */
    public static String uploadQrcodeToAliyun(String ticket) {
    	try {
	    	String path = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=%s";
	    	String url = String.format(path, URLEncoder.encode(ticket, "utf-8"));
	    	File file = WxFileUtils.downFile(url);
		
			return AliyunOssUploadUtils.uploadFile(file, ticket + ".jpg");
		} catch (Exception e) {
			log.error("上传ticket二维码图片到阿里云出现异常：{}", e.getMessage(), e);
		}
    	
    	return "";
    }
}
